package com.resjz.milddog.config;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.resjz.milddog.model.BaseUserDetail;
import com.resjz.milddog.model.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.bootstrap.encrypt.KeyProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.security.jwt.crypto.sign.RsaSigner;
import org.springframework.security.jwt.crypto.sign.Signer;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.security.KeyPair;
import java.util.Map;

/**
 * Created by fp295 on 2018/4/16.
 * 自定义JwtAccessToken转换器
 */
//@Component
public class JwtAccessToken extends JwtAccessTokenConverter {

    /****
     * JWT令牌转换器
     */
    //读取密钥的配置


    private JwtAccessTokenConverter converter ;
    private KeyPair keyPair;
    public JwtAccessToken(KeyProperties keyProperties) {
        //super();
        this.converter = new JwtAccessTokenConverter();
        // 导入证书
        this.keyPair = new KeyStoreKeyFactory(
                keyProperties.getKeyStore().getLocation(),                          //证书路径 changgou.jks
                keyProperties.getKeyStore().getSecret().toCharArray())              //证书秘钥 changgouapp
                .getKeyPair(
                        keyProperties.getKeyStore().getAlias(),                     //证书别名 changgou
                        keyProperties.getKeyStore().getPassword().toCharArray());   //证书密码 changgou
        converter.setKeyPair(keyPair);
    }
    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        DefaultOAuth2AccessToken defaultOAuth2AccessToken = new DefaultOAuth2AccessToken(accessToken);

        // 设置额外用户信息
        UserDto baseUser = ((BaseUserDetail) authentication.getPrincipal()).getBaseUser();
        //baseUser.setPassword(null);
        // 将用户信息添加到token额外信息中
       // defaultOAuth2AccessToken.getAdditionalInformation().put("user-info", baseUser);
        if(!this.isPublic()){
            this.setKeyPair(this.keyPair);
        }
        return super.enhance(defaultOAuth2AccessToken, authentication);
    }

    /**
     * 解析token
     * @param value
     * @param map
     * @return
     */
    @Override
    public OAuth2AccessToken extractAccessToken(String value, Map<String, ?> map){
        OAuth2AccessToken oauth2AccessToken = super.extractAccessToken(value, map);
        convertData(oauth2AccessToken, oauth2AccessToken.getAdditionalInformation());
        return oauth2AccessToken;
    }

    private void convertData(OAuth2AccessToken accessToken, Map<String, ?> map) {
        accessToken.getAdditionalInformation().put("user-info",convertUserData(map.get("user-info")));

    }

    private UserDto convertUserData(Object map) {
        ObjectMapper mapper = new ObjectMapper();
        String json ="";
        if (map == null) {
            return null;
        } else {
            try {
                json = mapper.writeValueAsString(map);
            } catch (JsonProcessingException var2) {
                return null;
            }
        }
        try {
            return mapper.readValue(json, UserDto.class);
        }catch (JsonProcessingException e){
            return null;
        }
    }
}
